<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="search-div">
      <el-row>
        <el-col :span="11" class="center-content"
          ><div class="grid-content bg-purple">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目编号/项目名称/客户名称"
              clearable
              @keyup.enter="handleQuery"
              style="width: 450px"
            /></div
        ></el-col>
        <el-col :span="7" class="center-content"
          ><div class="grid-content bg-purple-light">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择设计方案"
              clearable
              multiple
              style="width: 260px"
            >
              <el-option label="不限" value="all" />
              <el-option label="有" value="1" />
              <el-option label="无" value="0" />
            </el-select></div
        ></el-col>
        <el-col :span="6"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="doSearch">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button
              type="success"
              v-hasPermi="['project:projectData:addFurnace']"
              @click="addProject"
              >添加项目</el-button
            >
          </div></el-col
        >
      </el-row>
    </div>
    <el-dialog
      v-model="showDialog"
      :title="title"
      width="40%"
      @close="handleDialogClose"
      :close-on-click-modal="false"
    >
      <!-- 表单内容 -->
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="项目名称：" prop="projectName">
          <el-input
            v-model="form.projectName"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户名称：" prop="clientName">
          <el-select
            v-model="form.clientName"
            filterable
            placeholder="请输入客户名称"
            allow-create
          >
            <el-option
              v-for="item in options"
              :key="item.customerName"
              :label="item.customerName"
              :value="item.customerName"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表格区域 -->
    <div class="table-div">
      <div class="scrollable-table">
        <Pagetable
          :data="showProjectList"
          :columns="columns"
          :initialPageSize="10"
        >
          <template #actions="{ row }">
            <el-button
              type="primary"
              size="small"
              v-hasPermi="['project:projectData:handleFurnace']"
              @click="handleEdit(row)"
              >编辑</el-button
            >

            <el-button type="primary" size="small" @click="handleDetail(row)"
              >详情</el-button
            >
            <el-button
              v-show="false"
              type="primary"
              size="small"
              @click="designDetail(row)"
              >设计方案</el-button
            >

            <el-popconfirm
              title="确定要删除当前项目吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleConfirm(row)"
              v-hasPermi="['project:projectData:handleFurnace']"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  v-hasPermi="['project:projectData:handleFurnace']"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </Pagetable>
      </div>
    </div>
  </div>
</template>

<script setup>
import http from "@/utils/ajaxUtils";
import { onMounted } from "vue";
import router from "@/router";
import { ref } from "vue";
import request from "@/utils/request";
import { ElMessage, ElPopover, ElButton } from "element-plus";
import Pagetable from "@/components/MSTN/pagetable.vue";
import { useProjectNumber } from "@/utils/generateCode";

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  projectName: undefined,
  status: [],
});

const visible = ref(false);
const allProjectList = ref([]);
const showProjectList = ref([]);
const columns = [
  { prop: "projectName", label: "项目名称" },
  { prop: "customerName", label: "客户名称" },
  { prop: "projectStatus", label: "项目状态" },
  { prop: "projectCode", label: "项目编号" },
  { prop: "createTime", label: "项目创建时间" },
  {
    prop: "actions",
    label: "操作",
    width: 250,
    slot: "actions",
  },
];

const showDialog = ref(false);
const form = ref({
  projectName: "",
  clientName: "",
});
const formRef = ref(null);
const rules = {
  projectName: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
  clientName: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
};

const title = ref("新建项目");
//项目编号
const projectNumber = ref("");
const { generateProjectNumber } = useProjectNumber();

const generateNumber = () => {
  projectNumber.value = "编号" + generateProjectNumber();
};

//客户名称id
const options = ref([]);

function getList() {
  http
    .get("/system/project/list", { pageSize: 200 })
    .then((response) => {
      allProjectList.value = response.rows;
      showProjectList.value = response.rows;
    })
    .catch((error) => {
      console.error(error);
    });
}

function handleQuery() {
  showProjectList.value = allProjectList.value.filter((item) => {
    return (
      item.projectName.includes(queryParams.value.projectName) ||
      item.customerName.includes(queryParams.value.projectName) ||
      item.projectCode.includes(queryParams.value.projectName)
    );
  });
}

//搜索按钮
function doSearch() {
  if (
    queryParams.value.status.length > 0 &&
    queryParams.value.status[0] !== "all"
  ) {
    showProjectList.value = allProjectList.value.filter((item) => {
      return queryParams.value.status.includes(item.projectStatus);
    });
  }
  if (
    queryParams.value.projectName !== undefined &&
    queryParams.value.projectName != ""
  ) {
    handleQuery();
  }
}

function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    projectName: undefined,
    status: [],
  };
  showProjectList.value = allProjectList.value;
}

function handleDetail(row) {
  router.push(`/projects/projectData/detail/${row.projectId}`); // 根据实际路由调整
}

function handleEdit(row) {
  form.value.clientName = row.customerName;
  title.value = "编辑项目";
  form.value.projectName = row.projectName;
  form.value.projectId = row.projectId;
  showDialog.value = true;
}

//设计方案
function designDetail(row) {
  router.push(`/project/designDetailProject/${row.projectId}`);
}

//添加项目
function addProject() {
  form.value.projectName = "";
  form.value.clientName = "";
  title.value = "新建项目";
  showDialog.value = true;
}

//删除按钮
const handleConfirm = (row) => {
  http
    .post("/system/project/deleteProject/" + row.projectId)
    .then((response) => {
      ElMessage.success("删除成功！");
      getList();
    })
    .catch((error) => {
      console.error(error);
    });
};

function handleSave() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (title.value === "编辑项目") {
        request({
          url: "/system/project/editProject",
          method: "post",
          data: {
            projectId: form.value.projectId,
            projectName: form.value.projectName,
            customerName: form.value.clientName,
          },
        }).then((response) => {
          ElMessage.success("保存成功！");
          getList();
          form.value = { projectName: "", clientName: "" };
          showDialog.value = false;
        });
      } else {
        generateNumber();
        const params = ref({
          projectName: form.value.projectName,
          projectCode: projectNumber.value,
          customerName: form.value.clientName,
        });
        http
          .post("/system/project/", params.value)
          .then((response) => {
            ElMessage.success("保存成功！");
            getList();
            form.value = { projectName: "", clientName: "" };
            showDialog.value = false;
          })
          .catch((error) => {
            console.error(error);
          });
      }
    }
  });
}

// 对话框关闭事件
function handleDialogClose() {
  // 清空表单
  form.value = {
    projectName: "",
    clientName: "",
  };
}

//获取客户名称
function getCustomerName() {
  request({
    url: "/system/customer/list",
    method: "get",
    params: { customerName: "" },
  }).then((response) => {
    if (response.rows.length > 0) {
      options.value = response.rows;
    }
  });
}

onMounted(() => {
  getList();
  getCustomerName();
});
</script>

<style scoped>
.app-container {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.search-div {
  height: 7%;
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.table-div {
  height: calc(90% - 20px);
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.scrollable-table {
  overflow-y: auto; /* 启用垂直滚动条 */
  flex-grow: 1;
  height: 100%;
}

.center-content {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100%; /* 确保高度占满父容器 */
}
</style>
